<template>
  <div class="components-trend">
    <HeadBar
      :title="$t('dataAnalysis.commodityTrendAnalysis')"
      :date-options="dateOptions"
      :date-type="5"
      @date-change="onDateChange"
    >
      <template #default>
        <el-popover
          placement="right"
          width="500"
          trigger="click"
        >
          <el-form
            :model="customIndexForm"
            class="form-inline"
            @submit.prevent
          >
            <el-form-item :label="$t('dataAnalysis.productsOverview')">
              <el-checkbox-group v-model="customIndexForm.prodSurvey">
                <el-checkbox
                  :label="$t('dataAnalysis.numberOfNewProducts')"
                  name="prodSurvey"
                />
                <el-checkbox
                  :label="$t('dataAnalysis.goodsVisited')"
                  name="prodSurvey"
                />
                <el-checkbox
                  :label="$t('dataAnalysis.goodsSold')"
                  name="prodSurvey"
                />
              </el-checkbox-group>
            </el-form-item>
            <el-form-item :label="$t('dataAnalysis.commodityFlow')">
              <el-checkbox-group v-model="customIndexForm.prodFlow">
                <el-checkbox
                  :label="$t('dataAnalysis.shareVisits')"
                  name="prodSurvey"
                />
                <el-checkbox
                  :label="$t('dataAnalysis.productViews')"
                  name="prodSurvey"
                />
                <el-checkbox
                  :label="$t('dataAnalysis.productVisitors')"
                  name="prodSurvey"
                />
              </el-checkbox-group>
            </el-form-item>
            <el-form-item :label="$t('dataAnalysis.commodityConversion')">
              <el-checkbox-group v-model="customIndexForm.prodTransForm">
                <el-checkbox
                  :label="$t('dataAnalysis.carNumbers')"
                  name="prodSurvey"
                />
                <el-checkbox
                  :label="$t('dataAnalysis.orderCounts')"
                  name="prodSurvey"
                />
                <el-checkbox
                  :label="$t('dataAnalysis.payCounts')"
                  name="prodSurvey"
                />
              </el-checkbox-group>
            </el-form-item>
            <span id="maxSelectSpan">{{ $t("dataAnalysis.upTo") }} {{ maxSelectNum }}
              {{ $t("dataAnalysis.items") }}</span>
            <span>{{ $t("dataAnalysis.selected") }} {{ selectNum }}
              {{ $t("dataAnalysis.items") }}</span>
          </el-form>
          <template #reference>
            <el-button>
              {{
                $t("dataAnalysis.selectIndicators")
              }}
            </el-button>
          </template>
        </el-popover>
      </template>
    </HeadBar>
    <div
      id="time-survey"
      class="realtime-chart-box"
      style="width: 100%; height: 300px"
    />
  </div>
</template>

<script setup>
import HeadBar from './head-bar.vue'
import * as $echarts from 'echarts'

const dateOptions = [
  {
    label: $t('dataAnalysis.nearly7'),
    value: 5
  },
  {
    label: $t('dataAnalysis.nearly30'),
    value: 6
  },
  {
    label: $t('dataAnalysis.naturalMonth'),
    value: 3
  }
]

// 时间更新
// 2:近七天 3:近30天 5:自然月
let dateType = 2
let dateRange = []
const onDateChange = (data) => {
  dateRange = data.dateRange
  let tempType
  switch (data.timeType) {
    case 5:
      tempType = 2
      break
    case 6:
      tempType = 3
      break
    case 3:
      tempType = 5
      break
  }
  dateType = tempType
  getProdTrendAnalysis()
}

/**
 * 商品趋势分析数据
 */
const dateArr = ref([]) // 趋势图时间数组
let seriesDataArr = [] // 所有数据
const seriesControlDataArr = ref([]) // 控制显示的数据
const getProdTrendAnalysis = () => {
  http({
    url: http.adornUrl('/platform/prodAnalysis/getProdTrendAnalysis'),
    method: 'get',
    params: http.adornParams(
      {
        dateType,
        startTime: dateRange[0],
        endTime: dateRange[1]
      }
    )
  }).then(({ data }) => {
    if (data) {
      dateArr.value = []
      seriesDataArr = []
      const obj1 = initObj($t('dataAnalysis.numberOfNewProducts'))
      const obj2 = initObj($t('dataAnalysis.goodsVisited'))
      const obj3 = initObj($t('dataAnalysis.goodsSold'))
      const obj4 = initObj($t('dataAnalysis.shareVisits'))
      const obj5 = initObj($t('dataAnalysis.productViews'))
      const obj6 = initObj($t('dataAnalysis.productVisitors'))
      const obj7 = initObj($t('dataAnalysis.carNumbers'))
      const obj8 = initObj($t('dataAnalysis.orderCounts'))
      const obj9 = initObj($t('dataAnalysis.payCounts'))
      data.forEach(i => {
        dateArr.value.push(i.currentDay)
        obj1.data.push(i.newProd)
        obj2.data.push(i.visitedProd)
        obj3.data.push(i.dynamicSale)
        obj4.data.push(i.shareVisit)
        obj5.data.push(i.browse)
        obj6.data.push(i.visitor)
        obj7.data.push(i.addCart)
        obj8.data.push(i.orderNum)
        obj9.data.push(i.payNum)
      })
      seriesDataArr.push(obj1)
      seriesDataArr.push(obj2)
      seriesDataArr.push(obj3)
      seriesDataArr.push(obj4)
      seriesDataArr.push(obj5)
      seriesDataArr.push(obj6)
      seriesDataArr.push(obj7)
      seriesDataArr.push(obj8)
      seriesDataArr.push(obj9)
    }
    controlTrendDataShow()
    getRealTimechartData()
  })
}

/**
 * 商品趋势分析表
 */
let myChartTimeSurvey
const getRealTimechartData = () => {
  // 有的话就获取已有echarts实例的DOM节点
  myChartTimeSurvey = $echarts.getInstanceByDom(document.getElementById('time-survey'))
  // 如果不存在，就进行初始化
  if (myChartTimeSurvey == null) {
    myChartTimeSurvey = $echarts.init(document.getElementById('time-survey'))
  }
  const option = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: '#fff',
      padding: 8,
      textStyle: { // 提示框浮层的文本样式。
        fontSize: '12px',
        fontWeight: 400,
        color: '#33333',
        opacity: 1,
        lineHeight: '20px'
      },
      extraCssText: 'box-shadow:0px 1px 11px rgba(213, 220, 226, 0.73);'
    },
    legend: { // 图例配置
      data: sumData.value,
      selectedMode: false, // 关闭图例选择
      itemHeight: 8, // 图例标记的图形宽度。
      itemWidth: 18, // 图例标记的图形高度。
      icon: 'roundRect', // 图例项的 icon。
      itemGap: 40, // 图例每项之间的间隔
      textStyle: { // 图例的公用文本样式。
        color: '#999999',
        size: 12,
        padding: [0, 0, 0, 10]
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    // x轴的颜色和宽度
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dateArr.value,
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      },
      axisTick: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      axisLine: { show: false },
      axisTick: { show: false }
    },
    series: seriesControlDataArr.value
  }
  myChartTimeSurvey.setOption(option, true)
  window.addEventListener('resize', function () {
    myChartTimeSurvey.resize()
  })
}

/**
 * 初始化一个obj
 */
const initObj = (name) => {
  const obj = {}
  obj.name = name
  obj.type = 'line'
  obj.data = []
  return obj
}

const customIndexForm = reactive({
  prodSurvey: [], // '新增商品数', '被访问商品数', '动销商品数'
  prodFlow: [$t('dataAnalysis.shareVisits'), $t('dataAnalysis.productViews'), $t('dataAnalysis.productVisitors')],
  prodTransForm: []
})
const selectNum = ref(0)
const maxSelectNum = ref(3) // 最多选择几项
const sumData = ref([])
watch([() => customIndexForm.prodSurvey, () => customIndexForm.prodFlow, () => customIndexForm.prodTransForm], () => {
  selectNum.value = customIndexForm.prodSurvey.length + customIndexForm.prodFlow.length + customIndexForm.prodTransForm.length
  sumData.value = []
  sumData.value = sumData.value.concat(customIndexForm.prodSurvey).concat(customIndexForm.prodFlow).concat(customIndexForm.prodTransForm)
  const checks = document.getElementsByName('prodSurvey')
  const span = document.getElementById('maxSelectSpan')
  checks.forEach(i => {
    if (selectNum.value >= maxSelectNum.value) {
      textShare(span, 'red')
      if (!i.checked) {
        i.setAttribute('disabled', 'true')
      }
    }
  })
  if (selectNum.value < maxSelectNum.value) {
    textShare(span, 'black')
    checks.forEach(i => {
      i.removeAttribute('disabled')
    })
  }
}, { deep: true, immediate: true })

watch(() => sumData.value, () => {
  controlTrendDataShow()
})

const lineStyle = [
  {
    color: '#29CB97',
    lineStyle: {
      color: '#29CB97'
    }
  },
  {
    color: '#0058FF',
    lineStyle: {
      color: '#0058FF'
    }
  },
  {
    color: '#F56C6C',
    lineStyle: {
      color: '#F56C6C'
    }
  }
]
const areaStyle = [
  {
    color: new $echarts.graphic.LinearGradient(0, 0, 0, 1, [{
      offset: 0,
      color: 'rgba(41, 203, 151, 0.41)'
    }, {
      offset: 1,
      color: '#ffffff'
    }])
  },
  {
    color: new $echarts.graphic.LinearGradient(0, 0, 0, 1, [{
      offset: 0,
      color: 'rgba(24,144,255,0.6)'
    }, {
      offset: 1,
      color: '#ffffff'
    }])
  },
  {
    color: new $echarts.graphic.LinearGradient(0, 0, 0, 1, [{
      offset: 0,
      color: '#F56C6C'
    }, {
      offset: 1,
      color: '#ffffff'
    }])
  }
]

/**
 * 控制趋势图的数据显示
 */
const controlTrendDataShow = () => {
  seriesControlDataArr.value = []
  let length = 0
  sumData.value.forEach(i => {
    length = length + 1
    seriesDataArr.forEach(element => {
      if (i === element.name) {
        element.smooth = true
        element.itemStyle = lineStyle[length - 1]
        element.areaStyle = areaStyle[length - 1]
        seriesControlDataArr.value.push(element)
      }
    })
  })
  if (sumData.value.length < 1) {
    seriesControlDataArr.value = []
  }
  if (length === sumData.value.length) {
    getRealTimechartData()
  }
}
/**
 * 文字效果
 */
const textShare = (div, color) => {
  div.style.color = color
}
</script>

<style lang="scss" scoped>
.components-trend {
  margin: 20px 0 30px;
}
</style>
